/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package abricots.entity;

import abricots.command.Commandable;
import abricots.command.PlayerCommand;
import abricots.entity.command.BasicEntityCommandManager;
import abricots.entity.controller.KeyboardController;
import abricots.entity.state.BasicEntityStateManager;
import abricots.game.GameEnv;
import abricots.net.common.GameMessage.CommandsMessage;

/**
 *
 * @author charly
 */
public class PlayerEntity extends BasicEntity {

    private final KeyboardController controller;
    private Commandable commandable;

    public PlayerEntity(GameEnv env) {
        controller = new KeyboardController(this, env);
        stateManager = new BasicEntityStateManager(this);
    }

    @Override
    public void register(GameEnv env) {
        this.env = env;
        env.getEntitiesManager().addEntity(this);
    }

    public void processCommand(int commandId, boolean started) {
        if (commandable == null) {
            return;
        }
        PlayerCommand command = new PlayerCommand(env.getTimeManager().getGameTime(), commandId, started);
        commandable.processCommand(command);
    }

    public CommandsMessage buildCommandMessage(long fromTime, long toTime) {
        if (BasicEntityCommandManager.class.isAssignableFrom(commandable.getClass())) {
            BasicEntityCommandManager commandManager = (BasicEntityCommandManager) commandable;
            return commandManager.buildCommandMessage(fromTime, toTime);
        }
        CommandsMessage commandsMessage = new CommandsMessage();
        commandsMessage.fromTime = fromTime;
        commandsMessage.toTime = toTime;
        commandsMessage.entityId = id;
        return commandsMessage;
    }

    @Override
    public void onValidation() {
        env.getEntitiesManager().getRootEntity().addChild(id);
    }

    public KeyboardController getController() {
        return controller;
    }
}
